import axios from "axios";
import {useStore} from "@/store/user.js";
import {message} from "ant-design-vue";

const {VITE_APP_PROXY_TYPE, VITE_APP_PROXY_TARGET} = import.meta.env;

const service = axios.create({
    baseURL: VITE_APP_PROXY_TYPE,
    timeout: 50000,
});


// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const user = useStore();
        const token = user.token;
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        return response.data;
    },
    async (error) => {
        const originalRequest = error.config;
        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;
            try {
                const user = useStore();
                const refreshToken = user.refresh;
                const res = await axios.post(`${import.meta.env.VITE_APP_PROXY_TYPE}/token/refresh/`, {refresh: refreshToken});
                user.token = res.data.access;
                originalRequest.headers.Authorization = `Bearer ${user.token}`;
                return service(originalRequest);
            } catch (refreshError) {
                message.error("Token refresh failed:", refreshError);
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);

export default service;
